from django.http import JsonResponse, Http404
from django.shortcuts import render
# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, mixins, generics, viewsets
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAdminUser
from rest_framework import filters
from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Article, Category, Tag
# 这个 ArticleListSerializer 暂时还没有
from article.permissions import IsAdminuserOrReadOnly
from article.serializers import ArticleListSerializer, ArticleDetailSerializer, CategorySerializer, \
    CategoryDetailSerializer, TagSerializer, ArticleSerializer

'''
def article_list(request):
    articles = Article.objects.all()
    serializer = ArticleListSerializer(articles, many = True)
    return  JsonResponse(serializer.data,safe = False)
'''


@api_view(['GET', 'POST'])
def article_list(request):
    if request.method == 'GET':
        articles = Article.objects.all()
        serializer = ArticleListSerializer(articles, many=True)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == 'POST':
        serializer = ArticleListSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


'''
class ArticleDetail(APIView):
    
    #文章详情截图
    

    def get_object(self, pk):
        try:
            # pk  默认状态下id
            return Article.objects.get(pk=pk)
        except:
            raise Http404

    def get(self, request, pk):
        article = self.get_object(pk)
        serializer = ArticleDetailSerializer(article)
        # 返回json数据
        return Response(serializer.data)

    def put(self, request, pk):
        article = self.get_object(pk)
        serializer = ArticleDetailSerializer(article, data=request.data)
        # 验证提交的数据是否合法
        # 不合法则返回400
        if serializer.is_valid():
            # 序列化器将持有的数据反序列化后，
            # 保存到数据库中
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        article = self.get_object(pk)
        article.delete()
        # 删除成功返回204
        return Response(status=status.HTTP_204_NO_CONTENT)
'''

'''
class ArticleDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    """文章详情视图"""
    queryset = Article.objects.all()
    serializer_class = ArticleDetailSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

'''


class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleDetailSerializer
    permission_classes = [IsAdminuserOrReadOnly]


# class ArticleList(generics.ListCreateAPIView):
#     queryset = Article.objects.all()
#     serializer_class = ArticleListSerializer
#     # 新增
#     # permission_classes = [IsAdminUser]
#     permission_classes = [IsAdminuserOrReadOnly]
#
#     # 写入author
#     def perform_create(self, serializer):
#         serializer.save(author=self.request.user)


class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleListSerializer
    permission_classes = [IsAdminuserOrReadOnly]

    # 精准搜索：http://127.0.0.1:8000/api/article/?username=admin&title=title 1
    # filter_backends = [DjangoFilterBackend]
    # filterset_fields = ['author__username', 'title']
    filter_backends = [filters.SearchFilter]
    search_fields = ['title']

    def get_queryset(self):
        queryset = self.queryset
        username = self.request.query_params.get('username', None)
        if username is not None:
            queryset = queryset.filter(author__username=username)
        return queryset

    # 写入author
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)
    #
    # def get_serializer_class(self):
    #     if self.action == 'list':
    #         return  SomeSerializer
    #     else:
    #         return AnotherSerializer


def get_serializer_class(self):
    if self.action == 'list':
        return ArticleSerializer
    else:
        return ArticleDetailSerializer


class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_serializer_class(self):
        if self.action == 'list':
            return CategorySerializer
        else:
            return CategoryDetailSerializer
    # permission_classes = [IsAdminuserOrReadOnly]


class TagViewSet(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    # permission_classes = [IsAdminUserOrReadOnly]
